package com.example.asynctaskdemo.okhttp;

import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


/**
 * Created by xubp on Date: 2022/11/2
 */
public class NbzgmNetWorkRequest {
    private int dkpdpConnectTime =10000;
    private int dkpdpReadTime =10000;

    /**
     * ch
     * @param requestUrl
     * @param requestMethod
     */
    public NbzgmNetResponse qecrnNetWordRequst(String requestUrl, String requestMethod, String contextType, String body, Map<String, String> headerMap){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(dkpdpConnectTime);
            connection.setReadTimeout(dkpdpReadTime);
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);//可读入
            connection.setDoOutput(true);//可写出
            connection.setUseCaches(false);//不缓存
            if(!TextUtils.isEmpty(contextType)){
                connection.setRequestProperty("Content-Type", contextType);
            }
            if(headerMap!=null && headerMap.size()>0){
                for (String key:headerMap.keySet()){
                    connection.setRequestProperty(key,headerMap.get(key));
                }
            }
            connection.connect();//建立连接
            if(!TextUtils.isEmpty(body)){
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
                if(writer!=null){
                    writer.write(body);
                    writer.close();
                }
            }
            return qecrnGetNetResponse(connection);
        } catch (Throwable e) {
            e.printStackTrace();
            return qecrnExceptionResponse(connection,e);
        }

    }

    /**
     * 正常返回，获取response 对象
     * @param conn
     * @return
     */
    private NbzgmNetResponse qecrnGetNetResponse(HttpURLConnection conn){
        NbzgmNetResponse response = new NbzgmNetResponse();
        try {
            if(conn == null){
                return null;
            }
            response.dkpdpResponseCode = conn.getResponseCode();

            if(response.dkpdpResponseCode == HttpURLConnection.HTTP_OK){
                response.dkpdpResponseContent = qecrnGetResponeString(conn.getInputStream());
                response.dkpdpResponseCode = 200;//强制修改为200，判断200为成功接收就好了。
            }else{
                response.dkpdpResponseContent = qecrnGetResponeString(conn.getErrorStream());
            }
        } catch (Throwable e) {
            response.dkpdpResponseCode = -1;
            response.dkpdpResponseContent = e.getMessage();
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 异常返回，获取response 对象
     * @param conn
     * @param e
     * @return
     */
    private NbzgmNetResponse qecrnExceptionResponse(HttpURLConnection conn, Throwable e){
        if(conn != null){
            conn.disconnect();
        }
        if(e == null){
            return null;
        }
        e.printStackTrace();
        NbzgmNetResponse response = new NbzgmNetResponse();
        response.dkpdpResponseCode = -2;
        response.dkpdpResponseContent = e.getMessage();
        return response;
    }

    private String qecrnGetResponeString(InputStream is){
        String buf;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            buf = sb.toString();
            return buf;

        } catch (Throwable e) {
            return "";
        }

    }

}
